package com.example.common.service.impl;
import java.io.*;
import java.util.Date;

import cn.hutool.core.lang.Console;
import com.example.common.service.FileService;
import com.example.common.utils.RestResponse;
import com.example.user.entity.MyFile;
import com.example.user.mapper.MyFileMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: mtl
 * @Date: 2022/1/21 15:17
 * @Description:
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Value("${file.path}")
    private String path;

    @Value("${file.url}")
    private String url;

    @Resource
    public MyFileMapper fileMapper;


    @Override
    public RestResponse handleFileUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return RestResponse.failed("文件为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        String filePath = path;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        boolean b = saveFile(dest, suffixName);
        if(!b){
            RestResponse.failed("文件储存失败");
        }
        try {
            file.transferTo(dest);
            return RestResponse.succeed(dest);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return RestResponse.failed("上传失败");
    }

    @Override
    public boolean saveFile(File file,String suffixName) {
        MyFile myFile = new MyFile();
        myFile.setName(file.getName());
        myFile.setPath(file.getPath());
        myFile.setAccessPath(url+file.getName());
        myFile.setSuffix(suffixName);
        myFile.setCreator("admin");
        myFile.setCreateTime(new Date());
        myFile.setDeleteState(0);
        return 0<fileMapper.insert(myFile);
    }

    @Override
    public void downloadFile(Integer id, HttpServletResponse response) {
        MyFile myFile = fileMapper.selectById(id);
        try {
            // path是指欲下载的文件的路径。
            File file = new File(myFile.getPath());
            // 取得文件名。
            String filename = myFile.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}
